package com.wyl.login.activity

import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareConfig
import com.umeng.socialize.bean.SHARE_MEDIA
import com.wuhenzhizao.titlebar.widget.CommonTitleBar
import com.wyl.base.LoginPage
import com.wyl.base.TimetablePage
import com.wyl.libbase.base.BindingActivity
import com.wyl.libbase.extend.openActivity
import com.wyl.libbase.extend.toast
import com.wyl.libbase.utils.KLog
import com.wyl.login.BindPhoneActivity
import com.wyl.login.R
import com.wyl.login.databinding.LoginActivityBinding
import org.koin.android.viewmodel.ext.android.viewModel

const val PHONE = 3

@Route(path = LoginPage)
class LoginActivity : BindingActivity<LoginActivityBinding>() {
    private val viewModel: LoginViewModel by viewModel()

    private val mShareAPI by lazy { UMShareAPI.get(this) }

    override fun getLayoutId(): Int = R.layout.login_activity

    override fun initView() {
        binding.vm = viewModel

        binding.titlebar.setListener { _, action, _ ->
            when (action) {
                CommonTitleBar.ACTION_LEFT_BUTTON -> onBackPressed()
                else -> {
                }
            }
        }
    }

    override fun loadData() {
        viewModel.success.observe(this, Observer {
            openActivity(TimetablePage)
            finish()
        })
        viewModel.toast.observe(this, Observer { toast(it ?: "") })
        viewModel.bindPhone.observe(this, Observer {
            startActivityForResult(Intent(this, BindPhoneActivity::class.java), PHONE)
        })
        viewModel.error.observe(this, Observer { toast(it ?: "") })

        mShareAPI.setShareConfig(UMShareConfig().isNeedAuthOnGetUserInfo(true))
    }

    override fun onClick(v: View) = when (v.id) {
        R.id.tv_register -> startActivity(Intent(this, RegisterActivity::class.java))
        R.id.tv_forget -> startActivity(Intent(this, ForgetActivity::class.java))
        R.id.tv_agreement -> startActivity(Intent(this, AgreementActivity::class.java))
        R.id.iv_wx -> mShareAPI.getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener)
        R.id.iv_qq -> mShareAPI.getPlatformInfo(this, SHARE_MEDIA.QQ, authListener)
        else -> {
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mShareAPI.onActivityResult(requestCode, resultCode, data)

        if (resultCode != RESULT_OK) return
        if (requestCode == PHONE) {
            data?.apply {
                val phone = this.extras["phone"] as String
                viewModel.bindingPhone(phone)
            }
            return
        }
    }

    private var authListener: UMAuthListener = object : UMAuthListener {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        override fun onStart(platform: SHARE_MEDIA) {
            KLog.i("平台：" + platform.getName())
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        override fun onComplete(platform: SHARE_MEDIA, action: Int, data: Map<String, String>) {
            KLog.d("登陆成功")
            KLog.d("openid = ${data["openid"]}")
            KLog.d("uid = ${data["uid"]}")
            KLog.d("avatar = ${data["iconurl"]}")
            KLog.d("nickname = ${data["name"]}")
            if (platform == SHARE_MEDIA.QQ) {
                viewModel.qqid = data["openid"] ?: data["uid"] ?: ""
            } else {
                viewModel.wxid = data["openid"] ?: data["uid"] ?: ""
            }
            viewModel.platform = platform
            viewModel.avatar = data["iconurl"] ?: ""
            viewModel.nickname = data["name"] ?: ""
            viewModel.loginThree()
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, action: Int, t: Throwable) {
            KLog.d("第三方平台登录失败 ${t.message}")
            toast("第三方平台登录失败")
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        override fun onCancel(platform: SHARE_MEDIA, action: Int) {
            KLog.d("第三方平台登录授权取消")
            toast("第三方平台登录授权取消")
        }
    }
}

